/*
 * PoolFilter.java
 * 
 */

import java.io.IOException;
import java.net.URLEncoder;
import java.util.Enumeration;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * 
 * @author Hemant
 * This class is a servlet filter. Every request coming to POOL comes here first except
 * other filters.
 */
public class PoolFilter implements Filter 
{
	public void destroy() {
		// TODO Auto-generated method stub		
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException 
	{
		System.out.println("In Pool Filter");
		String RequestURI = ((HttpServletRequest)request).getRequestURI();
		System.out.println("RequestURI is   "+RequestURI);
		HttpServletRequest req = ((HttpServletRequest)request);
		
		Enumeration<Object> enum1 = req.getParameterNames();
				
		HttpSession session = req.getSession();
		
		while(enum1.hasMoreElements())
		{
			String param = (String)enum1.nextElement();
			String param_val = req.getParameter(param);
			
			System.out.println(param+"	"+param_val);
			
			if(!(param.equalsIgnoreCase("submit") || param.equalsIgnoreCase("reset")))
			{				
				if(param.equalsIgnoreCase("objectname"))
				{
					session.setAttribute("objectname", param_val);
					continue;
				}
				if(param.equalsIgnoreCase("process"))
				{
					session.setAttribute("process", param_val);
					continue;
				}			
			}
		}
		
		String url = null;
		RequestDispatcher rd = null;
		
		if(RequestURI.equalsIgnoreCase("/poolweb/"))
		{
			url = "Login.jsp";
		}
		else if(RequestURI.endsWith(".html") || RequestURI.endsWith(".htm"))
		{
			String [] temp = RequestURI.split("/");
			String page = temp[temp.length-1].split(".html")[0];
			System.out.println("The request page is "+page);			
			session.setAttribute("page",page);			
			url = "RequestHandlerServlet";
		}
		else
		{
			url = RequestURI.split("poolweb")[1];
		}
		
		request.removeAttribute("objectname");
		request.removeAttribute("process");
		
		System.out.println("The request url is "+url);
		rd = request.getRequestDispatcher(url);
		rd.forward(request, response);
	}

	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub		
	}
}
